import { useRouter } from "next/router";
import { useToast } from "@/fastgpt/web/hooks/useToast";
import { SetStateAction, useState } from "react";
import { defaultApp } from "../constants";
import { useRequest } from "ahooks";
import { getAppDetailById } from "../api";
import { createContext } from "use-context-selector";
import { AppDetailInterface } from "../type";

export const AppContext = createContext<any>({
  appDetail: defaultApp,
  setAppDetail: function (value: SetStateAction<AppDetailInterface>): void {
    throw new Error("Function not implemented.");
  },
  loadingApp: false,
  updateAppDetail: function (data: any): Promise<void> {
    throw new Error("Function not implemented.");
  },
  publishApp: function (data: any): Promise<void> {
    throw new Error("Function not implemented.");
  },
});

export const AppContextProvider = ({
  children,
  appId,
}: {
  children: any;
  appId: any;
}) => {
  const router = useRouter();
  const { toast } = useToast();
  const [appDetail, setAppDetail] = useState(defaultApp);
  const { loading } = useRequest(
    async () => {
      if (appId) {
        let data = await getAppDetailById(appId);
        console.log(data);
        return data;
        //
      }
      return Promise.resolve(defaultApp);
    },
    {
      refreshDeps: [appId],
      onSuccess(res) {
        console.log("success");
        setAppDetail(res);
      },
      onError(err: any) {
        console.log(err, 111);
        toast({
          title: err?.message || "core.app.error.Get app failed",
          status: "error",
        });
        // router.replace("/app/list");
      },
    }
  );

  const contextValue = {
    appDetail,
    setAppDetail,
    loadingApp: loading,
  };

  return (
    <AppContext.Provider value={contextValue}>{children}</AppContext.Provider>
  );
};
